﻿using HttpHelper;
using ICSharpCode.SharpZipLib.Zip;
using MicroTest_Client;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MicroTest
{
   
    public partial class FrmChooseExam : Form
    {
        
        public FrmChooseExam()
        {

            TransparencyKey= Color.FromArgb(0, 0, 0, 0);
            InitializeComponent();


        }
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        public string TestKey = string.Empty;
        BackgroundWorker backgroundWorker = null;
        private string UserName = string.Empty;
        private List<GradeStruct> gradeInfos = new List<GradeStruct>();
        private List<ClassStruct> classInfos = new List<ClassStruct>();
        //private List<SubjectStruct> subjectInfos = new List<SubjectStruct>();
        //private List<ExamStruct> examInfos = new List<ExamStruct>();
        private List<LxcStruct> lxcInfos = new List<LxcStruct>();
        private List<ZjStruct> zjInfos = new List<ZjStruct>();
        private string SchoolInfo = string.Empty;
        private string GradeInfo = string.Empty;
        private string ClassInfo = string.Empty;
        private string ExamInfo = string.Empty;
        private string ExamID = string.Empty;
        private string selectedLXCID = string.Empty;
        private string selectedZJID = string.Empty;
        private string selectedClassID = string.Empty;
        private string selectedGradeID = string.Empty;
        private string selectedZJ = string.Empty;
        private string BasePageSerial = string.Empty;
        private GradeStruct gradeStruct;
        private ClassStruct classStruct;
        //private string UserName;
        public void SetGradeInfo(string gradeID,string gradeName)
        {
            if (gradeStruct == null)
                gradeStruct = new GradeStruct();
            gradeStruct.GradeID = Convert.ToInt32(gradeID);
            gradeStruct.GradeStr = gradeName;
        }
        public void SetClassInfo(string classID, string className)
        {
            if (classStruct == null)
                classStruct = new ClassStruct();
            classStruct.ClassID = Convert.ToInt32(classID);
            classStruct.ClassStr = className;
        }
        public void SetUserInfo(string usr)
        {
            UserName = usr;
        }
        private void tbKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
               // btnLogin_Click(sender, e);
            }
        }
        private void LoadLxcByGrade()
        {

            GradeStruct gs = gradeStruct;
            ELogger.Trace(string.Format("选择年级【{0}】", gs.GradeStr));
            NetWorkMissonParameter para = new NetWorkMissonParameter();
            para.NMT = NetMissonType.NMT_BJ;
            string qString = string.Format("BJList?username={0}&njid={1}", UserName, gs.GradeID);
            para.Parameter = qString;
            if (!backgroundWorker.IsBusy)
            {
                selectedGradeID = gs.GradeID.ToString();
                EnableControls(false);
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                backgroundWorker.RunWorkerAsync(para);
            }

        }
        private void FrmStart_Load(object sender, EventArgs e)
        {
            
            transparentTabControl.MakeTransparent();
            transparentTabControl.Visible = false;
            //tbKey.Text = "F656905A-7710-4575-B24E-2D8791A075BF";
            transparentTabControl.SelectedIndex = 0;


            //labInfoBJ.Top = labTitleMc.Bottom + 10;
            //labBJ.Top = labInfoBJ.Top;

            //btnConfirm.Top = labInfoBJ.Bottom + 28;
            //btnReChoose.Left = btnConfirm.Right + 8;
            //btnReChoose.Top = btnConfirm.Top;

           // pnlInfo.Visible = false;

            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
            LoadLxcByGrade();
        }
        
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string queryString = string.Empty;
            NetWorkMissonParameter para = (NetWorkMissonParameter)e.Argument;
            NetCommunication net = new NetCommunication();
            string msg = string.Empty;
            bool ret = net.NetGetRequest(para.Parameter, ref msg);
            NetWorkMissonResult result = new NetWorkMissonResult();
            result.Success = ret;
            result.NMT = para.NMT;
            result.ReturnMessage = msg;
            if (para.NMT == NetMissonType.NMT_LOGIN && result.Success == true)
            {
                
                JObject ojb = JObject.Parse(msg);
                if (Convert.ToInt32(ojb["State"].ToString()) == 1)
                {
                    //年级
                    msg = string.Empty;
                    if (true == GetGradeList(UserName, ref msg))
                    {
                        string errMsg = string.Empty; ;
                        if (false == ParseGradeList(msg, ref errMsg))
                        {
                            result.Success = false;
                            result.ReturnMessage = errMsg;
                            e.Result = result;
                            return;
                        }
                    }
                    else
                    {
                        result.Success = false;
                        result.ReturnMessage = msg;
                        return;
                    }
                    //班级
                    if (gradeInfos.Count != 0)
                    {
                        string usr = UserName;
                        string njid = gradeInfos[0].GradeID.ToString();
                        msg = string.Empty;
                        //Program.MTInfo.MicroTestClassID=
                        if (true == GetClassList(usr, njid, ref msg))
                        {
                            string errMsg = string.Empty;
                            ParseClassList(msg, ref errMsg);
                        }
                    }
                    //学科
                    //msg = string.Empty;
                    //if(true==GetSubjectList(ref msg))
                    //{
                    //    string errMsg = string.Empty;
                    //    ParseSubjectList(msg, ref errMsg);
                    //}
                    //练习册列表
                    msg = string.Empty;
                    if (gradeInfos.Count != 0/*&&classInfos.Count!=0&&subjectInfos.Count!=0*/)
                    {
                        string usr = UserName;
                        string njid = gradeInfos[0].GradeID.ToString();
                        Program.MTInfo.MicroTestUserName = usr;
                        Program.MTInfo.MicroTestGradeID = njid;
                        if (true == GetLxcList(usr, njid, ref msg))
                        {
                            string errMsg = string.Empty;
                            ParseLxcList(msg, ref errMsg);
                        }
                    }
                    msg = string.Empty;
                    if (lxcInfos.Count != 0/*&&classInfos.Count!=0&&subjectInfos.Count!=0*/)
                    {
                        string usr = UserName;
                        string lxcid = lxcInfos[0].LxcID;
                        if (true == GetZjList(usr, lxcid, ref msg))
                        {
                            string errMsg = string.Empty;
                            ParseZjList(msg, ref errMsg);
                        }
                    }


                }
            }
            //Grade -> Class
            //Grade -> Lxc
            else if (para.NMT == NetMissonType.NMT_BJ && result.Success == true)
            {
                if (true)
                {
                    string errMsg = string.Empty;
                    if (false == ParseClassList(result.ReturnMessage, ref errMsg))
                    {
                        result.Success = false;
                        result.ReturnMessage = errMsg;
                        e.Result = result;
                    }
                    string msgTmp = string.Empty;
                    errMsg = string.Empty;
                    if (true == GetLxcList(UserName, selectedGradeID, ref msgTmp))
                    {
                        ParseLxcList(msgTmp, ref errMsg);
                    }
                }

            }
            //LXC -> ZJ
            else if (para.NMT == NetMissonType.NMT_ZJ && result.Success == true)
            {
                string errMsg = string.Empty;
                if (false == ParseZjList(result.ReturnMessage, ref errMsg))
                {
                    result.Success = false;
                    result.ReturnMessage = errMsg;
                    e.Result = result;
                    return;
                }
            }
            else if (para.NMT == NetMissonType.NMT_ST && result.Success == true)
            {
                string errMsg = string.Empty;
                if (false == ParseStudentList(result.ReturnMessage, ref errMsg))
                {
                    result.Success = false;
                    result.ReturnMessage = errMsg;
                    e.Result = result;
                    return;
                }

            }
            else if (para.NMT == NetMissonType.NMT_EXAM && result.Success == true)
            {
                string errMsg = string.Empty;
                if (false == ParseCreateExam(result.ReturnMessage, ref errMsg))
                {
                    result.Success = false;
                    result.ReturnMessage = errMsg;
                    e.Result = result;
                }

            }
            e.Result = result;
        }
        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            NetWorkMissonResult result =(NetWorkMissonResult) e.Result;
            EnableControls(true);
            ELogger.Trace(string.Format("MissonComplete-->{0}  {1}", result.NMT, result.Success));
            switch (result.NMT)
            {
                case NetMissonType.NMT_LOGIN:
                    break;
                case NetMissonType.NMT_NJ:
                    break;
                case NetMissonType.NMT_BJ:
                    this.Cursor = System.Windows.Forms.Cursors.Arrow;
                    if (result.Success == false)
                    {
                        MessageBox.Show("获取班级列表失败！\n" + result.ReturnMessage);
                        ELogger.Trace("获取班级列表失败！" + result.ReturnMessage);
                    }
                    else
                    {
                        combZj.Items.Clear();
                        zjInfos.Clear();
                        combLxc.Items.Clear();
                        combLxc.Items.AddRange(lxcInfos.ToArray());

                        combLxc.SelectedIndex = combLxc.Items.Count == 0 ? -1 : 0;
                    }
                    break;
                case NetMissonType.NMT_XK:
                    break;
                case NetMissonType.NMT_KS:
                    break;
                case NetMissonType.NMT_ST:
                    {
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        if (result.Success == false)
                        {
                            MessageBox.Show("获取学生列表失败！\n" + result.ReturnMessage);
                            ELogger.Error("获取学生列表失败！" + result.ReturnMessage);
                        }
                        else
                        {
                            
                            pnlInfo.Visible = true;
                            pnlChooseMicroTest.Visible = false;
                            //transparentTabControl.SelectedIndex = 3;
                            //this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            this.DialogResult = DialogResult.OK;
                            this.Close();

                        }
                    }
                    break;
                case NetMissonType.NMT_LXC:
                    break;
                case NetMissonType.NMT_ZJ:
                    {
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        if (result.Success == false)
                        {
                            MessageBox.Show("获取章节列表失败！\n" + result.ReturnMessage);
                            ELogger.Trace("获取章节列表失败！" + result.ReturnMessage);
                        }
                        else
                        {
                            combZj.Items.Clear();
                            combZj.Items.AddRange(zjInfos.ToArray());
                            combZj.SelectedIndex = combZj.Items.Count == 0 ? -1 : 0;
                        }
                    }
                    break;
                case NetMissonType.NMT_EXAM:
                    {
                        
                        if (result.Success == false)
                        {
                            this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            MessageBox.Show("创建考试失败！\n" + result.ReturnMessage);
                            ELogger.Trace("创建考试失败！" + result.ReturnMessage);
                        }
                        else
                        {
                            TestKey = Program.MTInfo.MicroTestID;
                            ELogger.Trace(string.Format("微测ID:{0}", TestKey));
                            ELogger.Trace(string.Format("学校信息：{0}", Program.MTInfo.MicroTestRoomInfo));
                            ELogger.Trace(string.Format("试卷名称:{0}", Program.MTInfo.MicroTestTitle));

                            string msgTmp = string.Empty;
                            if (true == GetPaperInfo(TestKey, ref msgTmp))
                            {
                                string errMsg = string.Empty;
                                if(ParsePaperInfo(msgTmp, ref errMsg))
                                {
                                    ELogger.Trace(string.Format("获取试卷基地址成功，基地址为：{0}", BasePageSerial));

                                    NetCommunication net = new NetCommunication();
                                    string dataFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\img.zip";
                                    if (File.Exists(dataFile))
                                        File.Delete(dataFile);
                                    string msg = string.Empty;
                                    bool b=net.NetDownLoadRequest(string.Format("get?type=BKIMG&id={0}", TestKey), dataFile, ref msg);
                                    if(b==true)
                                    {
                                        ExtractBackgroundImages(dataFile);
                                        ELogger.Trace("获取试卷背景图片成功");
                                    }
                                    else
                                    {
                                        ELogger.Error("获取试卷背景图片失败");

                                    }
                                }
                                else
                                {
                                    ELogger.Error(string.Format("解析试卷基地址失败"));

                                }
                            }
                            else
                            {
                                ELogger.Error(string.Format("获取试卷基地址失败"));

                            }
                            this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                    }
                    break;
                default:
                    break;
            }


        }
        private string AddPageAddres(string basePage,int index)
        {
            string[] parts = basePage.Split('.');
            int section = Convert.ToInt32(parts[0]);
            int shelf = Convert.ToInt32(parts[1]);
            int book = Convert.ToInt32(parts[2]);
            int page = Convert.ToInt32(parts[3]);
            page += index;
            if(section==1713&&page>107)
            {
                book++;
                page -= 108;
                if(book>52)
                {
                    shelf++;
                    book = 0;
                }
            }
            if(section==1536&&page>107)
            {
                book++;
                page -= 108;
                if (book > 72)
                {
                    shelf++;
                    book = 0;
                }
            }
            return string.Format("{0}.{1}.{2}.{3}", section, shelf, book, page);
        }
        private bool ExtractBackgroundImages(string path)
        {
            string desFolder= Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if (Directory.Exists(desFolder + "\\Images"))
                Directory.Delete(desFolder + "\\Images", true);
            try
            {
                FastZip zip = new FastZip();
                zip.ExtractZip(path, desFolder, "");
                // bunziped =ZipHelper.UnZip(path, desFolder);
            }
            catch (Exception ex)
            {
                ELogger.Error(string.Format("解压文件{0}失败，失败信息：{1}", path, ex.Message));
                return false;
            }
            
            desFolder = desFolder + "\\Images";
            DirectoryInfo di = new DirectoryInfo(desFolder);
            FileInfo[] fi = di.GetFiles();
            Program.MTInfo.ClearPaperPageImage();
            foreach (var item in fi)
            {
                string fileName = item.Name.Substring(0,item.Name.LastIndexOf('.'));
                string[] parts = fileName.Split('_');
                if(parts==null||parts.Length<3)
                {
                    ELogger.Error(string.Format("图片{0}文件名解析失败", fileName));
                    continue;
                }
                int index = Convert.ToInt32(parts[2])-1;
                if(string.IsNullOrEmpty(BasePageSerial))
                {
                    ELogger.Error("试卷基地址为空");
                    continue;
                }
                string pageSerial = AddPageAddres(BasePageSerial, index);
                string newBackgroundImagePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\Images\\" + pageSerial+".jpg";
                item.MoveTo(newBackgroundImagePath);
                Image img = Image.FromFile(newBackgroundImagePath);
                Image bitmap = new Bitmap(img,img.Width/2,img.Height/2);
                img.Dispose();
                Program.MTInfo.AddPaperPageImage(pageSerial, bitmap /*Image.FromFile(newBackgroundImagePath)*/);
                ELogger.Trace(string.Format("添加地址为{0}的试卷图片", pageSerial));
            }
            return true;


        }
        private void CombZj_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox com = sender as ComboBox;
            toolTipItem.Hide(com);
        }

        private void CombZj_DrawItem(object sender, DrawItemEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (cb.SelectedIndex == -1)
                return;
            
            // 绘制背景
            e.DrawBackground();
            //绘制列表项目
            e.Graphics.DrawString(cb.Items[e.Index].ToString(), e.Font, System.Drawing.Brushes.Black, e.Bounds);
            
            //将高亮的列表项目的文字传递到toolTip1(之前建立ToolTip的一个实例)
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                toolTipItem.Show(cb.Items[e.Index].ToString(), cb, e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height);
                ELogger.Trace(string.Format("{0} {1}", e.Bounds.X, e.Bounds.Y));
            }
            e.DrawFocusRectangle();

        }

        private void CombExam_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combZj.SelectedIndex == -1)
                return;
            ExamStruct es = (ExamStruct)combZj.SelectedItem;
            ELogger.Trace(string.Format("选择考试【{0}】,密钥【{1}】", es.ExamStr,es.ExamID));
        }

        

        

        
        private void EnableControls(bool enable)
        {
            //combLxc.Enabled = enable;
            
            //combZj.Enabled = enable;
            //btnChooseExam.Enabled = enable;
            //btnConfirm.Enabled = enable;
            //btnReChoose.Enabled = enable;
            //btnCancel.Enabled = enable;
            //lnkLogOut.Enabled = enable;
        }
        private bool GetGradeList(string UserName, ref string msg)
        {
            string qString = string.Format("NJList?username={0}", UserName);
            
            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseGradeList(string msg,ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            gradeInfos.Clear();
            SchoolInfo = gradeObj["ScName"].ToString();
            JArray gradeList = gradeObj["List"] as JArray;
            foreach (var item in gradeList)
            {
                int id = Convert.ToInt32(item["id"].ToString());
                string grade = item["name"].ToString();
                GradeStruct gs = new GradeStruct();
                gs.GradeID = id;
                gs.GradeStr = grade;
                gradeInfos.Add(gs);
            }
            return true;
        }
        private bool GetClassList(string UserName,string gradeID, ref string msg)
        {
            string qString = string.Format("BJList?username={0}&njid={1}", UserName,gradeID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseClassList(string msg, ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            classInfos.Clear();
            JArray gradeList = gradeObj["List"] as JArray;
            foreach (var item in gradeList)
            {
                int id = Convert.ToInt32(item["id"].ToString());
                string name = item["name"].ToString();
                ClassStruct gs = new ClassStruct();
                gs.ClassID = id;
                gs.ClassStr = name;
                classInfos.Add(gs);
            }
            return true;
        }

        

        private bool GetExamList(string usr,string njid,string bjid,string xkid,ref string msg)
        {
            string qString = string.Format("PaperList?username={0}&njid={1}&bjid={2}&xkid={3}", usr, njid, bjid, xkid);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        

        private bool ParseStudentList(string msg,ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            Program.MTInfo.ClearStudentCard();
            JArray gradeList = gradeObj["List"] as JArray;
            int count = 0;
            string str = string.Empty;
            try
            {
                foreach (var item in gradeList)
                {
                    str = item.ToString();
                    string name = item["name"].ToString();
                    int X = Convert.ToInt32(item["X"].ToString());
                    int Y = Convert.ToInt32(item["Y"].ToString());
                    int Width = Convert.ToInt32(item["Width"].ToString());
                    int Height = Convert.ToInt32(item["Height"].ToString());
                    string pageID = item["Pageid"].ToString();
                    StudentCard stc = new StudentCard();
                    stc.Name = name;
                    stc.LeftBound = X;
                    stc.TopBound = Y;
                    stc.CardWidth = Width;
                    stc.CardHeight = Height;
                    stc.PageId = pageID;
                    Program.MTInfo.AddStudentCard(stc);
                    ELogger.Info(string.Format("解析学生名单，第{0}个学生：{1}", ++count, name));
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                ELogger.Error(string.Format("解析学生名单失败！解析失败的字符串：{0},失败信息：{1}", str, errMsg));
                return false;
            }
            
            ELogger.Info(string.Format("名单解析完毕，共{0}个学生", count));
            //Program.MTInfo.MicroTestID = ExamID;
            Program.MTInfo.MicroTestTitle = selectedZJ;
            Program.MTInfo.MicroTestRoomInfo= SchoolInfo + GradeInfo + ClassInfo;
            //labMC.Text = Program.MTInfo.MicroTestTitle;
            //labBJ.Text = Program.MTInfo.MicroTestRoomInfo;
            UpdateExamInfo(labMC, Program.MTInfo.MicroTestTitle);
            UpdateExamInfo(labBJ, Program.MTInfo.MicroTestRoomInfo);

            return true;
        }
        private void UpdateExamInfo(Label lab,string txt)
        {
            if(this.InvokeRequired)
            {
                Action<Label, string> ac = new Action<Label, string>(UpdateExamInfo);
                this.Invoke(ac, new object[] { lab, txt });
            }
            else
            {
                lab.Text = txt;
          
            }
        }
        private bool GetLxcList(string UserName, string gradeID, ref string msg)
        {
            string qString = string.Format("LxcList?username={0}&njid={1}", UserName, gradeID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseLxcList(string msg, ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            lxcInfos.Clear();
            JArray lxcList = gradeObj["List"] as JArray;
            foreach (var item in lxcList)
            {
                string id = item["id"].ToString();
                string name = item["name"].ToString();
                LxcStruct ls = new LxcStruct();
                ls.LxcID = id;
                ls.LxcStr = name;
                lxcInfos.Add(ls);
            }
            return true;
        }

        private bool GetZjList(string UserName, string lxcID, ref string msg)
        {
            string qString = string.Format("zjList?username={0}&lxcid={1}", UserName, lxcID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseZjList(string msg, ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            zjInfos.Clear();
            JArray zjList = gradeObj["List"] as JArray;
            foreach (var item in zjList)
            {
                string id = item["id"].ToString();
                string name = item["name"].ToString();
                ZjStruct zj = new ZjStruct();
                zj.ZjID = id;
                zj.ZjStr = name;
                zjInfos.Add(zj);
            }
            return true;
        }
        private bool GetPaperInfo(string examID, ref string msg)
        {
            string qString = string.Format("weiceinfo?weiceid={0}", examID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        
        private bool ParsePaperInfo(string msg, ref string errMsg)
        {
            JObject paperObj = JObject.Parse(msg);
            if (Convert.ToInt32(paperObj["State"]) != 1)
            {
                errMsg = paperObj["Message"].ToString();
                return false;
            }
            BasePageSerial = paperObj["PageID"].ToString();

            return true;
        }
        private bool CreateExam(string UserName,string njid,string bjid,string lxcid,string zjid, ref string msg)
        {
            string qString = string.Format("CreateExam?username={0}&njid={1}&bjid={2}&lxcid={3}&zjid={4}", UserName, njid, bjid, lxcid, zjid);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseCreateExam(string msg,ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            zjInfos.Clear();
            JObject item = gradeObj["WeiCe"] as JObject;
            //foreach (var item in zjList)
            //{
                string id = item["id"].ToString();
                string name = item["name"].ToString();
                ExamID=id;
                ExamInfo = name;
            //}
            Program.MTInfo.MicroTestID = ExamID;
            Program.MTInfo.MicroTestTitle = ExamInfo;
            ELogger.Trace(string.Format("创建考试成功!考试名【{0}】密钥【{1}】", ExamInfo, ExamID));
            return true;
        }

        const int WM_NCLBUTTONDOWN = 0xA1;
        const int HT_CAPTION = 0x2;
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        // 窗体上鼠标按下时
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left & this.WindowState == FormWindowState.Normal)
            {
                // 移动窗体
                this.Capture = false;
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

       

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }


        private void btnConfirm_Click(object sender, EventArgs e)
        {
            
            //创建考试！！！
            if (backgroundWorker.IsBusy)
                return;
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            NetMissonType nty = NetMissonType.NMT_EXAM;
            NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
            netWorkMissionPara.NMT = nty;
            EnableControls(false);

            string queryString = string.Format("CreateExam?username={0}&njid={1}&bjid={2}&lxcid={3}&zjid={4}", UserName, selectedGradeID,selectedClassID,selectedLXCID,selectedZJID);
            netWorkMissionPara.Parameter = queryString;
            backgroundWorker.RunWorkerAsync(netWorkMissionPara);
        }

        private void btnReChoose_Click(object sender, EventArgs e)
        {
            labTitle.Text = "选择考试";

            transparentTabControl.SelectedIndex = 0;
        }


        private void labMC_Enter(object sender, EventArgs e)
        {
            toolTipKSMC.IsBalloon = true;
            toolTipKSMC.SetToolTip(this.labMC, labMC.Text);
        }

        private void labMC_MouseEnter(object sender, EventArgs e)
        {
            toolTipKSMC.IsBalloon = false;
            toolTipKSMC.SetToolTip(this.labMC, labMC.Text);
        }

        private void labBJ_MouseEnter(object sender, EventArgs e)
        {
            toolTipKSMC.IsBalloon = false;
            toolTipKSMC.SetToolTip(this.labBJ, labBJ.Text);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

       

        private void label6_Click(object sender, EventArgs e)
        {

        }

        
        
        private void btnChooseMT_Click(object sender, EventArgs e)
        {
            
            
        }
        //练习册变化->章节变化
        private void combLxc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combLxc.SelectedIndex == -1)
                return;
            toolTipItem.SetToolTip(sender as ComboBox, ((sender as ComboBox).SelectedItem.ToString()));

            LxcStruct ls = (LxcStruct)combLxc.SelectedItem;
            NetWorkMissonParameter para = new NetWorkMissonParameter();
            para.NMT = NetMissonType.NMT_ZJ;
            GradeStruct gs = gradeStruct;
            //SubjectStruct ss = (SubjectStruct)combLxc.SelectedItem;
            ELogger.Trace(string.Format("选择练习册【{0}】，对应年级【{1}】，学科【{2}】", ls.LxcStr, gs.GradeStr, "其它"));

            string qString = string.Format("zjList?username={0}&lxcid={1}", UserName,  ls.LxcID);
            para.Parameter = qString;
            if (!backgroundWorker.IsBusy)
            {
                EnableControls(false);
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                backgroundWorker.RunWorkerAsync(para);
            }
        }

        private void combZj_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combZj.SelectedIndex == -1)
                return;
            toolTipItem.SetToolTip(sender as ComboBox,((sender as ComboBox).SelectedItem.ToString()));
            ZjStruct zj = (ZjStruct)combZj.SelectedItem;
            LxcStruct lxc = (LxcStruct)combLxc.SelectedItem;
            string lx = lxc == null ? "空" : lxc.LxcStr;
            //SubjectStruct ss = (SubjectStruct)combLxc.SelectedItem;
        }

        

        private void btnChooseExam_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
                return;
            if (
                combLxc.SelectedIndex == -1 ||
                combZj.SelectedIndex == -1)
            {
                MessageBox.Show("考试信息不完整！");
                return;
            }
            if (backgroundWorker.IsBusy)
                return;

            GradeStruct gs = gradeStruct;
            ClassStruct cs = classStruct;
            ZjStruct zj = combZj.SelectedItem as ZjStruct;
            LxcStruct lxc = combLxc.SelectedItem as LxcStruct;
            GradeInfo = gs.GradeStr;
            ClassInfo = cs.ClassStr;
            selectedLXCID = lxc.LxcID;
            selectedZJID = zj.ZjID;
            selectedZJ = zj.ZjStr;
            selectedClassID = cs.ClassID.ToString();
            selectedGradeID = gs.GradeID.ToString();
            ELogger.Trace(string.Format("选择考试：{0} {1}  {2} {3}", GradeInfo, ClassInfo, lxc.LxcStr, zj.ZjStr));
            //StuList?username=zxy111&njid=13&bjid=1
            labBJ.Text = Program.MTInfo.MicroTestRoomInfo;
            labMC.Text = zj.ZjStr;
            Program.MTInfo.MicroTestTitle = zj.ZjStr;
            labTitle.Text = "确认考试";
            transparentTabControl.SelectedIndex = 1;
        }

        private void Panel_Paint(object sender, PaintEventArgs e)
        {
            Panel pan = sender as Panel;
            
            Color clr = Color.FromArgb(224, 236, 238);
            ControlPaint.DrawBorder(e.Graphics,
                                pan.ClientRectangle,
                                clr,//7f9db9
                                ButtonBorderStyle.Solid);
        }

        private void combLxc_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
                return;
            if (e.State.HasFlag(DrawItemState.ComboBoxEdit) || !e.State.HasFlag(DrawItemState.Focus))
            {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
                e.Graphics.DrawString(combLxc.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
            }
            else
            {
                //e.DrawBackground();
                Color clrs = Color.FromArgb(227, 190, 141);
                e.Graphics.FillRectangle(new SolidBrush(clrs), e.Bounds);
                e.Graphics.DrawString(combLxc.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
                if (Control.MousePosition.IsEmpty == false)
                {
                    int x = Control.MousePosition.X;
                    int y = Control.MousePosition.Y;
                    Point p = combLxc.PointToClient(new Point(x, y));
                    toolTipItem.Show(combLxc.Items[e.Index].ToString(), combLxc, e.Bounds.Width + 10, p.Y + e.Bounds.Height);

                }
                else
                    toolTipItem.Show(combLxc.Items[e.Index].ToString(), combLxc, e.Bounds.Width + 10, 0);

            }
        }

        private void combZj_DrawItem_1(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
                return;
            if (e.State.HasFlag(DrawItemState.ComboBoxEdit) || !e.State.HasFlag(DrawItemState.Focus))
            {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
                e.Graphics.DrawString(combZj.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
            }
            else
            {
                //e.DrawBackground();
                Color clrs = Color.FromArgb(227, 190, 141);
                e.Graphics.FillRectangle(new SolidBrush(clrs), e.Bounds);
                e.Graphics.DrawString(combZj.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
                if (Control.MousePosition.IsEmpty == false)
                {
                    int x = Control.MousePosition.X;
                    int y = Control.MousePosition.Y;
                    Point p = combZj.PointToClient(new Point(x, y));
                    toolTipItem.Show(combZj.Items[e.Index].ToString(), combZj, e.Bounds.Width + 10, p.Y + e.Bounds.Height);

                }
                else
                    toolTipItem.Show(combZj.Items[e.Index].ToString(), combZj, e.Bounds.Width + 10, 0);

            }
        }
        private void Comb_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox com = sender as ComboBox;
            toolTipItem.Hide(com);
        }
    }
   
}
